using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MyApp.WebApi.Entity;
using MyApp.WebApi.ParamModel;
using MyApp.WebApi.Repository;
using MyApp.WebApi.Utils;

namespace Admin3000.Backend.Controllers
{
    //商城管理列表
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class ShoppingMallsController : ControllerBase
    {
        private IRepository<ShoppingMalls> _shoppingMallsRespository;

        private readonly IWebHostEnvironment _hostingEnvironment;

        private TokenParameter _tokenParameter;

        private readonly IConfiguration _configuration;

        public ShoppingMallsController(
            IConfiguration configuration,
            IRepository<ShoppingMalls> shoppingMallsRespository,
            IWebHostEnvironment hostingEnvironment
        )
        {
            _hostingEnvironment = hostingEnvironment;
            _configuration = configuration;
            _shoppingMallsRespository = shoppingMallsRespository;
            _tokenParameter =
                _configuration
                    .GetSection("TokenParameter")
                    .Get<TokenParameter>();
        }

        //获取商城管理列表
        [HttpGet, Route("getlist")]
        public dynamic GetList()
        {
            var list = _shoppingMallsRespository.Table.ToList();
            return list;
        }

        //指定id商城信息
        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var mallId = _shoppingMallsRespository.GetById(id);

            if (mallId == null)
            {
                return new { Code = 1000, Data = "", Msg = "指定信息不存在" };
            }
            return new {
                Code = 1000,
                Data = mallId,
                Msg = "获取商城信息列表成功^_^"
            };
        }

        //商城管理表分页
        [HttpGet]
        public dynamic Get([FromQuery] Pager pager)
        {
            var pageIndex = pager.PageIndex;
            var pageSize = pager.PageSize;
            var rowsTotal = pager.RowsTotal;

            // 获得所有满足条件的记录
            var users =
                _shoppingMallsRespository
                    .Table
                    .Where(x => x.IsDeleted == false);

            //  var users = from program in _shoppingMallsRespository.Table
            //             join articleprogram in _articleRespository.Table on program.Id equals articleprogram.ProgramId
            //             orderby articleprogram.Id
            //             select new
            //             {
            //                 Id = program.Id,
            //                IsActived = program.IsActived,
            //                 IsDeleted = program.IsDeleted,
            //                 CreatedTime = program.CreatedTime,
            //                 Remarks = program.Remarks
            //             };
            // 对获得的记录分页
            var u =
                users.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // 返回的数据里，带有数据和分页信息
            var res =
                new {
                    Code = 1000,
                    Data =
                        new {
                            Data = u,
                            Pager =
                                new {
                                    pageIndex,
                                    pageSize,
                                    rowsTotal = users.Count()
                                }
                        },
                    Msg = "获取商城管理列表成功^_^"
                };
            return res;
        }


        // 商城管理表添加
        [HttpPost]
        public string Post()
        {
            var files = HttpContext.Request.Form.Files;
            string webRootPath = _hostingEnvironment.WebRootPath; // ...Api/wwwroot

            var mallName = HttpContext.Request.Form["mallName"].ToString();
            var icp = HttpContext.Request.Form["icp"].ToString();
            var publicSafe = HttpContext.Request.Form["public"].ToString();
            var logo = PictureHelper.getFilePath(files, "upload", webRootPath);

            if (
                string.IsNullOrEmpty(mallName) &&
                string.IsNullOrEmpty(logo) &&
                string.IsNullOrEmpty(icp) &&
                string.IsNullOrEmpty(publicSafe)
            )
            {
                var tmp =
                    new {
                        Code = 1004,
                        Data = "",
                        Msg = "商城信息不能为空，请确认后重试"
                    };
                return JsonHelper.Serialize(tmp);
            }

            var mall =
                new ShoppingMalls {
                    MallName = mallName,
                    ICP = icp,
                    Public = publicSafe ,
                     Logo = logo
                };

            _shoppingMallsRespository.Insert (mall);

            var res =
                new { Code = 1000, Data = mall, Msg = "添加商城管理信息成功" };
            return JsonHelper.Serialize(res);
        }

        // 商城管理表修改指定id
        [HttpPut("{id}")]
        public dynamic Put(int id)
        {
            var ShoppingMallsId = _shoppingMallsRespository.GetById(id);
            var files = HttpContext.Request.Form.Files;
            string webRootPath = _hostingEnvironment.WebRootPath; // ...Api/wwwroot
            var logo = PictureHelper.getFilePath(files, "upload", webRootPath);
            var mallName = HttpContext.Request.Form["mallName"].ToString();
            var icp = HttpContext.Request.Form["icp"].ToString();
            var publicSafe = HttpContext.Request.Form["public"].ToString();

            if (ShoppingMallsId != null)
            {
                ShoppingMallsId.MallName = mallName;
                ShoppingMallsId.ICP = icp;
                ShoppingMallsId.Public = publicSafe;
                ShoppingMallsId.Logo = logo;

                // user.Password = model.Password;
                ShoppingMallsId.UpdatedTime = DateTime.Now;
                _shoppingMallsRespository.Update (ShoppingMallsId);
                return JsonHelper
                    .Serialize(new {
                        Code = 1000,
                        Data = ShoppingMallsId,
                        Msg =
                            string
                                .Format("你修改商城管理的id为：{0}，已经修改成功，请注意查收",
                                id)
                    });
            }
            else
            {
                return JsonHelper
                    .Serialize(new {
                        Code = 104,
                        Data = "",
                        Msg = "指定Id的商城管理不存在，请确认后重试"
                    });
            }
        }
               //修改状态
        [HttpPost, Route("IsActived/{id}")]
        public dynamic IsActived(int id, NewShoppingMalls model)
        {
            var user = _shoppingMallsRespository.GetById(id);
                var num = model.IsActived;
            if (user != null)
            {
                if (num == false)
                {
                    user.IsActived = false;
                    user.UpdatedTime = DateTime.Now;
                    _shoppingMallsRespository.Update (user);
                    return JsonHelper
                        .Serialize(new {
                            Code = 200,
                            Data = user,
                            Msg = "禁用成功"
                        });
                }
                else
                {
                    user.IsActived = true;
                    user.UpdatedTime = DateTime.Now;
                    _shoppingMallsRespository.Update (user);
                    return JsonHelper
                        .Serialize(new {
                            Code = 200,
                            Data = user,
                            Msg ="启用成功"
                        });
                }
            }
            return JsonHelper
                .Serialize(new { Code = 104, Data = user, Msg = "修改失败" });
        }

        // 商城管理表删除
        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            var AritpId = _shoppingMallsRespository.GetById(id);
            if (AritpId != null)
            {
                AritpId.IsDeleted = true;
                return new {
                    Code = 1000,
                    Msg = string.Format("删除指定id为{0}的商城管理成功", id)
                };
            }
            else
            {
                return new {
                    Code = 104,
                    Data = "",
                    Msg = "指定Id的商城管理不存在，请确认后重试"
                };
            }
        }
    }
}
